<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, maximum-scale=1.0, initial-scale=1, user-scalable=0">
    <!-- 引入样式文件 -->
    <link rel="stylesheet" href="{{ asset('css/vant.index.css') }}"/>
    <link rel="stylesheet" href="{{ asset('css/chatroom.css') }}"/>
    <title>数治科技-聊天</title>
</head>
<body>
<div class="wrap-view">
    <div class="dialog-view" id="dialog-view">
        <!-- <div class="timeview">2020-09-20 06:50</div> -->
        @if(!empty($chatRecords))
            @foreach($chatRecords as $k => $record)
                @if($userId != $record['userid'])
                    <div class="chatview leftview">
                        <div class="chatleft">
                            <img src="{{$record['avatar']}}" alt="{{$record['username']}}">
                        </div>
                        <div class="chatright">
                            <div class="name">{{$record['username']}}</div>
                            @isset($record['message_type'])
                                @if($record['message_type'] == 'text')
                                    <div class="chat-content">
                                        {{$record['content']}}
                                    </div>
                                @elseif($record['message_type'] == 'voice')
                                    <div class="chat-content">
                                        <div class="voice-content" data-src="{{$record['content']}}" data-self="0">
                                            <img class="play-voice" src="{{ asset('img/yuyinzuo.png') }}" alt="">
                                            <b class="voice-duration">{{$record['duration']}}"</b>
                                        </div>
                                    </div>
                                @elseif($record['message_type'] == 'image')
                                    <div class="chat-content">
                                        <img onclick="previewImage('<?php echo $record['content']?>')" class="chat-image" src="{{ $record['content'] }}" alt="">
                                    </div>
                                @endif
                            @else
                                <div class="chat-content">
                                    {{$record['content']}}
                                </div>
                            @endisset
                        </div>
                    </div>
                @else
                    <div class="chatview rightview">
                        <div class="chatright">
                            <div class="name">{{$record['username']}}</div>
                            @isset($record['message_type'])
                                @if($record['message_type'] == 'text')
                                    <div class="chat-content">
                                        {{$record['content']}}
                                    </div>
                                @elseif($record['message_type'] == 'voice')
                                    <div class="chat-content">
                                        <div class="voice-content" data-src="{{$record['content']}}" data-self="1">
                                            <b class="voice-duration">{{$record['duration']}}"</b>
                                            <img class="play-voice" src="{{ asset('img/yuyinyou.png') }}" alt="">
                                        </div>
                                    </div>
                                @elseif($record['message_type'] == 'image')
                                    <div class="chat-content">
                                        <img onclick="previewImage('<?php echo $record['content']?>')" class="chat-image" src="{{ $record['content'] }}" alt="">
                                    </div>
                                @endif
                            @else
                                <div class="chat-content">
                                    {{$record['content']}}
                                </div>
                            @endisset
                        </div>
                        <div class="chatleft">
                            <img src="{{$record['avatar']}}" alt="{{$record['username']}}">
                        </div>
                    </div>
                @endif
            @endforeach
        @endif
    </div>
    <div class="sendwrap">
        <div class="sendview" id="text" style="margin-top: 0.15rem">
            <img src="{{ asset('img/yuyin.png') }}" class="msg-icon" onclick="changeMessageType('voice')">
            <input type="text" id="chat-text" class="input">
            <button id="sendMsg" class="sendbtn">发送</button>
            <img for="img-input" src="{{ asset('img/upload_img.png') }}" class="msg-icon" style="margin-left: 0.15rem" onclick="sendImg()">
        </div>
        <div class="sendview" id="voice" style="display: none">
            <img src="{{ asset('img/jianpan.png') }}" class="msg-icon" onclick="changeMessageType('text')">
            <button class="sendvoicebtn">按住说话</button>
        </div>

    </div>

    <!--按下说话-->
    <div class="press_box">
        <div class="press_main">
            <img class="press_voice2" src="{{ asset('img/mic.png') }}" alt="">
        </div>
        <div class="press_main2">
            <img class="press_voice2" src="{{ asset('img/yuyinchehui.png') }}" alt="">
        </div>
        <p class="press_text">手指上划,取消发送</p>
    </div>
    <div class="press_box2">
        <div class="press_main3">
            <img class="press_voice2" src="{{ asset('img/point.png') }}" alt="">
        </div>
        <p class="press_text2">说话时间太短</p>
    </div>
    <div class="press_box3">
        <p class="press_text3">10</p>
        <p class="press_text4">手指上划,取消发送</p>
    </div>
</div>
</body>

<!-- 引入 Vue 和 Vant 的 JS 文件 -->
<script src="{{ asset('js/url.min.js') }}"></script>
<script src="{{ asset('js/vue.min.js') }}"></script>
<script src="{{ asset('js/vant.min.js') }}"></script>
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script src="{{ asset('js/recorder.mp3.min.js') }}"></script>
<script src="{{ asset('js/rem.js') }}"></script>

<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
    wx.config(<?php echo $config;?>);
</script>

<script>

    var audio = null
    var posStart = 0;//初始化起点坐标
    var posEnd = 0;//初始化终点坐标
    var posMove = 0;//初始化终点坐标
    // 禁止浏览器右键功能
    document.oncontextmenu = function () {
        return false;
    }

    var rec;
    /**调用open打开录音请求好录音权限**/
    var recOpen = function (success) { //一般在显示出录音按钮或相关的录音界面时进行此方法调用，后面用户点击开始录音时就能畅通无阻了
        rec = Recorder({
            type: "mp3",
            sampleRate: 16000,
            bitRate: 16, //mp3格式，指定采样率hz、比特率kbps，其他参数使用默认配置；注意：是数字的参数必须提供数字，不要用字符串；需要使用的type类型，需提前把格式支持文件加载进来，比如使用wav格式需要提前加载wav.js编码引擎
            // onProcess: function(buffers, powerLevel){
            //     $(".recpowerx").css("height", powerLevel+"%");
            // }
        });
        rec.open(function () { //打开麦克风授权获得相关资源
            success && success();
        }, function (msg, isUserNotAllow) { //用户拒绝未授权或不支持
            alert((isUserNotAllow ? "UserNotAllow，" : "") + "无法录音:" + msg);
        });
    };


    var ws;
    var timeConnect = 0;
    var data = {
        roomId: url('?roomid'),
        client: url('?client'),
        userId: url('?userid'),
    }

    const toast = vant.Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
    });

    // 滚动到最后一条消息
    function toLastMessage() {
        var dialogView = document.getElementById('dialog-view');
        dialogView.scrollTop = dialogView.scrollHeight;
    }

    function isNull(str) {
        if (str == "") return true;
        var regu = "^[ ]+$";
        var re = new RegExp(regu);
        return re.test(str);
    }

    function sendImg() {
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: function (data) {
                var localIds = data.localIds[0].toString();
                wxUploadImage(localIds);
            }
        });
    }

    function wxUploadImage(localId) {
        wx.uploadImage({
            localId: localId,
            isShowProgressTips: 1,
            success: function (res) {
                if (res.errMsg == 'uploadImage:ok') {
                    uploadImageToAliYun(res.serverId)
                }
            }
        });
    }

    function previewImage(url) {
        wx.previewImage({
            current: url, // 当前显示图片的 http 链接
            urls: [url] // 需要预览的图片 http 链接列表
        });


    }

    // 切换消息发送类型
    function changeMessageType(type) {
        localStorage.setItem('message_type', type)
        $('#text').hide()
        $('#voice').hide()
        switch (type) {
            case 'text':
                $('#text').show()
                break;
            case 'voice':
                recOpen()
                $('#voice').show()
                break;
        }
    }

    // 发送消息
    function sendMsg() {
        var content = $('#chat-text').val()
        if (isNull(content)) return false
        var result = Object.assign(data, {type: 'say', content: content, message_type: 'text'})
        ws.send(JSON.stringify(result))
        $('#chat-text').val('')
        $('#chat-text').focus()
    }

    // 发送语音
    $('.sendvoicebtn').on('touchstart', function (event) {
        event.preventDefault();//阻止浏览器默认行为
        posStart = 0;
        posStart = event.originalEvent.targetTouches[0].pageY;//获取起点坐标
        $(this).text('松开 结束')
        $('.press_box').show()
        rec.start();
    })

    // 发送语音
    $('.sendvoicebtn').on('touchmove', function (event) {
        event.preventDefault()
        posMove = 0;
        posMove = event.originalEvent.changedTouches[0].pageY;//获取终点坐标
        if (posStart - posMove > 50) {
            $('.press_text').text('松开手指，取消发送')
            $('.press_main').hide()
            $('.press_main2').show()
        } else {
            $('.press_text').text('手指上划，取消发送')
            $('.press_main').show()
            $('.press_main2').hide()
        }
    })

    $('.sendvoicebtn').on('touchend', function (event) {
        $(this).text('按住 说话')
        $('.press_text').text('手指上划，取消发送')
        $('.press_main').show()
        $('.press_main2').hide()
        $('.press_box').hide()
        event.preventDefault();
        posEnd = 0;
        posEnd = event.originalEvent.changedTouches[0].pageY;//获取终点坐标
        rec.stop(function (blob, duration) {
            console.log(blob, (window.URL || webkitURL).createObjectURL(blob), "时长:" + duration + "ms");
            // var audio = (window.URL || webkitURL).createObjectURL(blob)
            // var time = Math.round(duration / 1000)
            if (duration < 500) {
                $('.press_box').hide()
                $('.press_box2').show()
                setTimeout(function () {
                    $('.press_box2').hide()
                }, 500)
                return false
            }

            if (posStart - posEnd > 50) {
                return false
            }

            // 声音文件存储到后台
            uploadVoiceToAliYun(blob, duration)
        })
    })

    function uploadImageToAliYun(serverId) {
        $.ajax({
            url: '/chatroom/download', //上传接口地址
            type: "GET",
            data: {media_id: serverId},
            success: function (v) {
                console.log(v)
                v = JSON.parse(v)
                if (v.success === true) {
                    // 发送到websocket
                    var result = Object.assign(data, {
                        type: 'say',
                        content: v.message,
                        message_type: 'image'
                    })
                    ws.send(JSON.stringify(result))
                } else {
                    vant.Toast.fail(v.message)
                }
            },
            error: function (s) {
                console.error("上传失败", s);
            }
        });
    }

    function uploadVoiceToAliYun(blob, duration) {
        let formData = new FormData()
        formData.append('file', blob, new Date().getTime() + '.mp3');
        formData.append('biz', "chatroom");
        formData.append("chatroom", "1");
        console.log(formData)

        $.ajax({
            url: '/jeecg-boot/sys/common/upload', //上传接口地址
            type: "POST",
            contentType: false, //让xhr自动处理Content-Type header，multipart/form-data需要生成随机的boundary
            processData: false, //不要处理data，让xhr自动处理
            data: formData,
            success: function (v) {
                if (v.success === true) {
                    // 发送到websocket
                    var result = Object.assign(data, {
                        type: 'say',
                        content: v.message,
                        message_type: 'voice',
                        duration: duration
                    })
                    ws.send(JSON.stringify(result))
                } else {
                    vant.Toast.fail(v.message)
                }
            },
            error: function (s) {
                console.error("上传失败", s);
            }
        });
    }

    // webSocket初始化
    function webSocketInit() {

        let proto = document.location.protocol === 'https:' ? 'wss' : 'ws';

        ws = new WebSocket(proto + "://" + document.domain + "/ws");

        ws.onopen = function (evt) {
            var result = Object.assign(data, {type: 'login'})
            console.log("websocket握手成功，发送登录数据:" + data);
            ws.send(JSON.stringify(result));
            toast.clear()
        };

        ws.onmessage = function (evt) {
            var msg = JSON.parse(evt.data);
            switch (msg.type) {
                case 'error':
                    alert(msg.msg)
                    ws.close()
                    break;
                case 'say':
                    // 在同一个聊天室内
                    if (data.roomId == msg.room_id) {

                        let contentArr = []
                        // 是否为本人发送的消息
                        if (data.userId != msg.userid) {
                            contentArr = [
                                '<div class="chatview leftview">',
                                '<div class="chatleft"><img src="' + msg.avatar + '" alt="' + msg.username + '"></div>',
                                '<div class="chatright"><div class="name">' + msg.username + '</div>',
                                '#content#',
                                '</div>',
                                '</div>'
                            ]
                        } else {
                            contentArr = [
                                '<div class="chatview rightview">',
                                '<div class="chatright"><div class="name">' + msg.username + '</div>',
                                '#content#',
                                '</div>',
                                '<div class="chatleft"><img src="' + msg.avatar + '" alt="' + msg.username + '"></div>',
                                '</div>'
                            ]
                        }

                        const index = contentArr.indexOf("#content#");
                        let str;
                        switch (msg.message_type) {
                            case 'text':
                                str = ['<div class="chat-content">' + msg.content + '</div>']
                                break;
                            case 'voice':
                                if (data.userId != msg.userid) {
                                    str = [
                                        '<div class="chat-content">',
                                        '<div class="voice-content" data-src="' + msg.content + '" data-self="0">',
                                        '<img class="play-voice" src="{{ asset('img/yuyinzuo.png') }}" alt="">',
                                        '<b class="voice-duration">' + msg.duration + '"</b>',
                                        '</div>',
                                        '</div>'
                                    ]
                                } else {
                                    str = [
                                        '<div class="chat-content">',
                                        '<div class="voice-content" data-src="' + msg.content + '" data-self="1">',
                                        '<b class="voice-duration">' + msg.duration + '"</b>',
                                        '<img class="play-voice" src="{{ asset('img/yuyinyou.png') }}" alt="">',
                                        '</div>',
                                        '</div>'
                                    ]
                                }
                                break;
                                case 'image':
                                    str = [
                                        '<div class="chat-content">',
                                            '<img class="chat-image" onclick="previewImage(\''+msg.content+'\')" src="'+ msg.content +'" alt="">',
                                        '</div>'
                                    ]
                                break;
                            default:
                                str = ['<div class="chat-content">' + msg.content + '</div>']
                                break;
                        }

                        if (index !== false) {
                            contentArr[index] = str.join("")
                        }

                        $('.dialog-view').append(contentArr.join(""))
                        toLastMessage()
                    }
                    break;
            }
        };

        ws.onclose = function (evt) {
            console.log("Connection closed.");
            reconnect();
        };
    }

    // 重连
    function reconnect() {
        // lockReconnect加锁，防止onclose、onerror两次重连
        timeConnect++;
        console.log("第" + timeConnect + "次重连");
        // 进行重连
        setTimeout(function () {
            webSocketInit();
        }, 1000);

    }

    function setDefaultMessageType() {
        const defaultMessageType = localStorage.getItem('message_type')
        if (defaultMessageType) {
            changeMessageType(defaultMessageType)
        }
    }

    function rollbackVoiceIcon() {

        $('.play-voice').each(function (index, ele) {
            var parent = $(ele).parent()
            var isSelf = $(parent).data('self')
            if (isSelf == '0') {
                $(ele).attr('src', "{{ asset('img/yuyinzuo.png') }}")
            } else {
                $(ele).attr('src', "{{ asset('img/yuyinyou.png') }}")
            }
        })

    }

    function isWechat() {
        let ua = navigator.userAgent.toLowerCase()
        console.log(navigator.userAgent.toLowerCase())
        if (ua.match(/MicroMessenger/i) && !ua.match(/wxwork/i)) {
            return true
        } else {
            return false
        }
    }

    $(function () {
        toLastMessage()
        webSocketInit()
        setDefaultMessageType()
        isWechat()
        // input 监听回车事件
        $("#chat-text").keydown(function (e) {
            // 当 keyCode 是13时,是回车操作
            if (e.keyCode == 13) {
                sendMsg()
                // 取消之前的keydown事件
                e.preventDefault();
            }
        })
        $('#sendMsg').click(function () {
            sendMsg()
        })


        // 播放语音消息
        $('.dialog-view').on('click', '.voice-content', function () {
            if (audio == null) {
                audio = document.createElement('audio') //生成一个audio元素
            } else {
                rollbackVoiceIcon()
                audio.pause()
            }
            const isSelf = $(this).data('self')
            if (isSelf == '0') {
                $(this).find('.play-voice').attr('src', "{{ asset('img/yuyinzuo.gif') }}")
            } else {
                $(this).find('.play-voice').attr('src', "{{ asset('img/yuyinyou.gif') }}")
            }
            audio.currentTime = 0;
            audio.src = $(this).data('src')
            audio.play();

            audio.addEventListener('ended', function () {
                rollbackVoiceIcon()
            }, false);
        })
    })
</script>
</html>
